﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.IO;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Data.SqlClient;
using System.Drawing;
using System.Drawing.Imaging;
using System.Xml.Linq;
using System.Threading;
using System.Globalization;
using Nivdal.AuxCode;
using System.Web.Script.Services;

namespace Nivdal
{
    public partial class NationalTeam : System.Web.UI.Page
    {
        public enum ResizeOptions
        {
            // Use fixed width & height without keeping the proportions
            ExactWidthAndHeight,

            // Use maximum width (as defined) and keeping the proportions
            MaxWidth,

            // Use maximum height (as defined) and keeping the proportions
            MaxHeight,

            // Use maximum width or height (the biggest) and keeping the proportions
            MaxWidthAndHeight
        }
        
        protected void Page_Load(object sender, EventArgs e)
        {
            GetNivdalData.GetNivdalData GND = new GetNivdalData.GetNivdalData();
            OnlineUser ou = (OnlineUser)Session["User"];

            string TeamId = "";

            if (Request.QueryString["Id"] != null)
            {
                TeamId = Request.QueryString["Id"];
            }
            else
            {
                if (ou.NationalTeamCoach == "0")
                    Response.Redirect("~/TeamHomePage.aspx");
                else
                    TeamId = ou.NationalTeamCoach;
            }

            TeamIdHiddenField.Value = TeamId;

            if (!IsPostBack)
            {
                TeamInfoDataSource.SelectParameters.Add("NTTeamId", TeamId);
                TeamInfoDataSource.SelectParameters.Add("Language", ou.Language);
                InvitesDataSource.SelectParameters.Add("NTTeamId", TeamId);
                TropheySqlDataSource.SelectParameters.Add("TeamId", TeamId);
                TropheySqlDataSource.SelectParameters.Add("National", "1");
                
                PrevMatchDataSource.SelectParameters.Add("TeamId", TeamId);
                PrevMatchDataSource.SelectParameters.Add("IsNational", "1");
                NextMatchDataSourse.SelectParameters.Add("TeamId", TeamId);
                if(ou.UserId != null)
                    NextMatchDataSourse.SelectParameters.Add("UserId", ou.UserId);
                NextMatchDataSourse.SelectParameters.Add("IsNational", "1");

                StadiumsDataSource.SelectParameters.Add("NTTeamId", TeamId);

                (TeamFormView.FindControl("InviteToFriendlyLink") as HyperLink).Visible =
                    GND.ReadNivdalBoolData("Team1", "Team2", "Nivdal_CanTwoNTTeamsPlayFriendly", ou.NationalTeamCoach, TeamId);
            }

            try
            {
                bool CanEditDetails = (ou.NationalTeamCoach == TeamId);
                (TeamFormView.FindControl("ManagerPanel") as Panel).Visible = CanEditDetails;
                (TeamFormView.FindControl("EditStadium") as ImageButton).Visible = CanEditDetails;
                (TeamFormView.FindControl("EditLogo") as LinkButton).Visible = CanEditDetails;
                if (CanEditDetails)
                {
                    (TeamFormView.FindControl("EditLogo") as Button).OnClientClick = "return confirm('" + Resources.Resource.UploadLogoConformationText + "')";

                }
                else
                {
                    (TeamFormView.FindControl("StatusUpdatePanel") as UpdatePanel).Visible = false;
                }
            }
            catch { }
        }

        protected bool InviteToFriendlyVisibile()
        {
            OnlineUser ou = (OnlineUser)Session["User"];
            return ((ou.NationalTeamCoach != "0") && (ou.NationalTeamCoach != TeamIdHiddenField.Value));
        }

        public bool IsAllowedLive(Object CanAddToLive)
        {
            GlobalFunctions GF = new GlobalFunctions();
            return GF.IsAllowedLive(CanAddToLive);
        }

        protected override void InitializeCulture()
        {
            OnlineUser ou = (OnlineUser)Session["User"];
            Thread.CurrentThread.CurrentUICulture = new CultureInfo(ou.UICulture);
            Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture(ou.Culture);
        }

        protected void BookmarkButton_Click(object sender, EventArgs e)
        {
            GetNivdalData.GetNivdalData GND = new GetNivdalData.GetNivdalData();
            OnlineUser ou = (OnlineUser)Session["User"];
            string TeamId = this.TeamIdHiddenField.Value;

            bool Success = true;

            string conn = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;            
            
            System.Data.IDbConnection dbConnection = new System.Data.SqlClient.SqlConnection(conn);
            System.Data.IDbCommand dbCommand = new System.Data.SqlClient.SqlCommand();
            dbCommand.CommandText = "Nivdal_BookmarkTeam";
            dbCommand.CommandType = CommandType.StoredProcedure;
            dbCommand.Connection = dbConnection;

            SqlParameter dbParam_UserId = new SqlParameter();
            dbParam_UserId.ParameterName = "@UserId";
            dbParam_UserId.Value = ou.UserId;
            dbParam_UserId.DbType = DbType.String;
            dbCommand.Parameters.Add(dbParam_UserId);

            SqlParameter dbParam_BookmarkedPlayer = new SqlParameter();
            dbParam_BookmarkedPlayer.ParameterName = "@BookmarkedTeam";
            dbParam_BookmarkedPlayer.Value = TeamId;
            dbParam_BookmarkedPlayer.DbType = DbType.String;
            dbCommand.Parameters.Add(dbParam_BookmarkedPlayer);

            SqlParameter dbParam_BookmarkType = new SqlParameter();
            dbParam_BookmarkedPlayer.ParameterName = "@National";
            dbParam_BookmarkedPlayer.Value = "1";
            dbParam_BookmarkedPlayer.DbType = DbType.Boolean;
            dbCommand.Parameters.Add(dbParam_BookmarkType);

            SqlParameter dbParam_Answer = new SqlParameter();
            dbParam_Answer.ParameterName = "@Answer";
            dbParam_Answer.Value = "";
            dbParam_Answer.DbType = DbType.String;
            dbParam_Answer.Direction = ParameterDirection.Output;
            dbParam_Answer.Size = 64;
            dbCommand.Parameters.Add(dbParam_Answer);

            try
            {
                dbConnection.Open();
                dbCommand.ExecuteScalar();
                
            }
            //catch (Exception SQLDBException)
            //{
            //    this.ErrorLabel.Text = Convert.ToString(SQLDBException);
            //}
            catch { Success = false; }
            finally
            {
                dbConnection.Close();
            }
            
            if (Success) 
                Response.Redirect("Bookmarks.aspx?ConfirmNote=" + dbParam_Answer.Value.ToString());
        }

        protected void ProposeFriendly(object sender, EventArgs e)
        { 
            // TBD
        }

        protected void SubmitNewStatus(object sender, EventArgs e)
        { 
            GetNivdalData.GetNivdalData GND = new GetNivdalData.GetNivdalData();
            OnlineUser ou = (OnlineUser)Session["User"];
            try
            {
                string NewStatus = (TeamFormView.FindControl("StatusTextBox") as TextBox).Text.Trim();
                string NTTeamId = TeamIdHiddenField.Value;
                GND.ExecNivdalSQL("NTTeamId", "Status", "Nivdal_NTSubmitNewStatus", NTTeamId, NewStatus);
                TeamFormView.DataBind();
            }
            catch { }
        }

        protected string InstructionsImage(object InstructionsNeeded)
        {
            if (InstructionsNeeded.ToString() == "1")
                return ("~/Images/Icons/add Instructions.gif");
            if (InstructionsNeeded.ToString() == "2")
                return ("~/Images/Icons/edit Instructions.png");
            return "";
        }

        protected string InstructionsToolTip(object InstructionsNeeded)
        {
            if (InstructionsNeeded.ToString() == "1")
                return (Resources.Resource.MatchPage_AssignInstructions);
            if (InstructionsNeeded.ToString() == "2")
                return (Resources.Resource.MatchPage_EditInstructions);
            return "";
        }

        protected bool InstructionsVisible(object InstructionsNeeded)
        {
            if (InstructionsNeeded.ToString() == "1" || InstructionsNeeded.ToString() == "2")
                return (true);
            return (false);
        }
        
        
       
        protected  void SubmitStadium(object sender, EventArgs e)
        { 
            
            GetNivdalData.GetNivdalData GND = new GetNivdalData.GetNivdalData();
            OnlineUser ou = (OnlineUser)Session["User"];
            DropDownList StadiumDDL = TeamFormView.FindControl("StadiumsDDL") as DropDownList;
            string StadiumId = StadiumDDL.SelectedValue;
            string StadiumName = StadiumDDL.SelectedItem.Text;

            if (GND.ReadNivdalBoolData("UserId", "NTTeamId", "StadiumId", "Nivdal_NTSubmitDefaultStadium", ou.UserId, TeamIdHiddenField.Value, StadiumId))
            {
                HyperLink StadiumLink = TeamFormView.FindControl("DefaultStadiumLink") as HyperLink;
                StadiumLink.NavigateUrl = "~/StadiumPage.aspx?StadiumId=" + StadiumId;
                StadiumLink.Text = StadiumName;
                MessagePanel.Visible = false;
            }
            else
            {
                MessagePanel.Visible = true;
                MessageLabel.Text = Resources.Resource.failure;

            }
        }

        protected void UploadTeamLogoButton_Click(object sender, EventArgs e)
        {
            GetNivdalData.GetNivdalData GND = new GetNivdalData.GetNivdalData();
            OnlineUser ou = (OnlineUser)Session["User"];
            FileUpload TeamLogoFileUpload = TeamFormView.FindControl("TeamLogoFileUpload") as FileUpload;
            
            if (TeamLogoFileUpload.HasFile)
            {

                string TeamuploadDirectory = Path.Combine(Request.PhysicalApplicationPath, "TeamLogos");

                // getting current image - the one that will be deleted
                string CurrentImageURL = GND.ReadNivdalStringData("TeamId", "IsNTTeam", "Nivdal_GetTeamLogo", TeamIdHiddenField.Value, "1");
                string ImageName = CurrentImageURL.Substring(CurrentImageURL.LastIndexOf('/') + 1);

                string num = DateTime.Now.Year.ToString() + DateTime.Now.DayOfYear.ToString() +
                    DateTime.Now.Hour.ToString() + DateTime.Now.Minute.ToString() +
                    DateTime.Now.Second.ToString() + DateTime.Now.Millisecond.ToString();

                int intFileSizeLimit = 5000000;
                bool IsImageInput;
                string extension = Path.GetExtension(TeamLogoFileUpload.PostedFile.FileName);
                string filenameNoExtension = Path.GetFileNameWithoutExtension(TeamLogoFileUpload.PostedFile.FileName);

                string ServerfileName = num + extension;
                string FullUploadPath = Path.Combine(TeamuploadDirectory, ServerfileName);
                string ImagePath = "~/TeamLogos/" + ServerfileName;

                if (!(TeamLogoFileUpload.HasFile && TeamLogoFileUpload.PostedFile != null))//first check if the user uploaded file
                    IsImageInput = false;//There is no image file

                else //There is image input
                    IsImageInput = true;

                //check if the image file has the right extantion and size
                if (IsImageInput && CheckImgFile(extension) && TeamLogoFileUpload.PostedFile.ContentLength / 1024 < intFileSizeLimit)
                {
                    System.Drawing.Bitmap ResizedTeamLogo = ResizeImgFile(new System.Drawing.Bitmap(TeamLogoFileUpload.PostedFile.InputStream), 150, 150);

                    try
                    {
                        //ResizedTeamLogo.SetResolution(150,150);
                        ResizedTeamLogo.Save(FullUploadPath);
                    }
                    catch (Exception err)
                    {
                        MessagePanel.Visible = true;
                        MessageLabel.Text = err.Message;
                        IsImageInput = false;
                    }
                }
                else
                {
                    MessagePanel.Visible = true;
                    MessageLabel.Text = Resources.Resource.Preferences_LeftImageFileError + " " + intFileSizeLimit + Resources.Resource.Preferences_RightImageFileError + " ";
                }

                if (IsImageInput)
                    GND.ExecNivdalSQL("UserId", "Logo", "IsNTTeam", "Nivdal_SetTeamLogo", ou.UserId, ImagePath, "1");

                System.Web.UI.WebControls.Image ActualImage =
                    (TeamFormView.FindControl("TeamLogImage") as System.Web.UI.WebControls.Image);

                ActualImage.ImageUrl = ImagePath;

                // deleting the old file
                if (!CurrentImageURL.Contains("menupicture.gif"))
                {
                    File.Delete((MapPath(".") + ("\\TeamLogos\\" + ImageName)));
                }

            }
            else
            {
                MessagePanel.Visible = true;
                MessageLabel.Text = Resources.Resource.ForumDetails_NoDataLabel;
            }
        }

        public string ReplaceEOL(object Text)
        {
            return GetNivdalData.GetNivdalData.ReplaceLineBreaks(Text);
        }
        protected void AddMatchToLive(object sender, FormViewCommandEventArgs e)
        {
            if (e.CommandName == "AddToLive")
            {
                GetNivdalData.GetNivdalData GND = new GetNivdalData.GetNivdalData();
                OnlineUser ou = (OnlineUser)Session["User"];
                GND.ExecNivdalSQL("UserId", "MatchId", "Nivdal_LiveAddMatchToLive", ou.UserId, e.CommandArgument);
                Response.Redirect("Live.aspx");
            }
        }

        #region resize functions
        
        private System.Drawing.Bitmap ResizeImgFile(System.Drawing.Bitmap img, int width, int height)
        {

            System.Drawing.Bitmap ResizedImg = ResizeImage(img, width, height, ResizeOptions.MaxWidthAndHeight);
            return ResizedImg;

        }

        

        public System.Drawing.Bitmap DoResize(System.Drawing.Bitmap originalImg, int widthInPixels, int heightInPixels)
        {
            System.Drawing.Bitmap bitmap;
            try
            {
                bitmap = new System.Drawing.Bitmap(widthInPixels, heightInPixels);
                using (System.Drawing.Graphics graphic = System.Drawing.Graphics.FromImage(bitmap))
                {
                    // Quality properties
                    graphic.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
                    graphic.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
                    graphic.PixelOffsetMode = System.Drawing.Drawing2D.PixelOffsetMode.HighQuality;
                    graphic.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;

                    graphic.DrawImage(originalImg, 0, 0, widthInPixels, heightInPixels);
                    return bitmap;
                }
            }
            finally
            {
                if (originalImg != null)
                {
                    originalImg.Dispose();
                }
            }
        }
               

        public System.Drawing.Bitmap ResizeImage(System.Drawing.Bitmap image, int width, int height, ResizeOptions resizeOptions)
        {
            float f_width;
            float f_height;
            float dim;
            switch (resizeOptions)
            {
                case ResizeOptions.ExactWidthAndHeight:
                    return DoResize(image, width, height);

                case ResizeOptions.MaxHeight:
                    f_width = image.Width;
                    f_height = image.Height;

                    if (f_height <= height)
                        return DoResize(image, (int)f_width, (int)f_height);

                    dim = f_width / f_height;
                    width = (int)((float)(height) * dim);
                    return DoResize(image, width, height);

                case ResizeOptions.MaxWidth:
                    f_width = image.Width;
                    f_height = image.Height;

                    if (f_width <= width)
                        return DoResize(image, (int)f_width, (int)f_height);

                    dim = f_width / f_height;
                    height = (int)((float)(width) / dim);
                    return DoResize(image, width, height);

                case ResizeOptions.MaxWidthAndHeight:
                    int tmpHeight = height;
                    int tmpWidth = width;
                    f_width = image.Width;
                    f_height = image.Height;

                    if (f_width <= width && f_height <= height)
                        return DoResize(image, (int)f_width, (int)f_height);

                    dim = f_width / f_height;

                    // Check if the width is ok
                    if (f_width < width)
                        width = (int)f_width;
                    height = (int)((float)(width) / dim);
                    // The width is too width
                    if (height > tmpHeight)
                    {
                        if (f_height < tmpHeight)
                            height = (int)f_height;
                        else
                            height = tmpHeight;
                        width = (int)((float)(height) * dim);
                    }
                    return DoResize(image, width, height);
                default:
                    return image;
            }
        }


        public bool CheckImgFile(string FileExtantion)
        {

            if (FileExtantion.Equals(".jpg") || (FileExtantion.Equals(".gif")) || (FileExtantion.Equals(".bmp")) || (FileExtantion.Equals(".png")))
                return true;
            else
                return false;
        }
        #endregion Resize functions
    }
}